<template>
  <view class="container">
    <u-form :model="form" ref="uForm">
      <u-form-item label="标题" prop="title" :required="true">
        <u-input v-model="form.title" placeholder="请输入愿望标题" />
      </u-form-item>
      
      <u-form-item label="描述" prop="description">
        <u-input
          v-model="form.description"
          type="textarea"
          placeholder="请输入愿望描述"
          height="150"
        />
      </u-form-item>
      
      <u-form-item label="状态" prop="status">
        <u-radio-group v-model="form.status">
          <u-radio v-for="(item, index) in statusOptions" :key="index" :name="item.value">
            {{ item.label }}
          </u-radio>
        </u-radio-group>
      </u-form-item>
      
      <u-form-item label="进度" prop="progress">
        <view class="progress-slider">
          <text class="slider-value">{{ form.progress }}%</text>
          <u-slider
            v-model="form.progress"
            :step="5"
            :blockSize="28"
          ></u-slider>
        </view>
      </u-form-item>
      
      <u-form-item label="预计实现时间" prop="estimated_time">
        <u-input
          v-model="form.estimated_time"
          placeholder="请选择预计实现时间"
          disabled
          @click="showDatePicker = true"
        />
      </u-form-item>
      
      <view class="form-actions">
        <u-button type="primary" @click="submitForm">保存</u-button>
        <u-button @click="goBack">取消</u-button>
      </view>
    </u-form>
    
    <u-picker
      mode="time"
      v-model="showDatePicker"
      :params="datePickerParams"
      @confirm="onDateConfirm"
    ></u-picker>
  </view>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { formatDate } from '@/utils/date'

export default {
  data() {
    return {
      id: null,
      isEdit: false,
      form: {
        title: '',
        description: '',
        status: 0,
        progress: 0,
        estimated_time: ''
      },
      statusOptions: [
        { label: '未开始', value: 0 },
        { label: '进行中', value: 1 },
        { label: '已实现', value: 2 }
      ],
      showDatePicker: false,
      datePickerParams: {
        year: true,
        month: true,
        day: true,
        hour: false,
        minute: false,
        second: false
      }
    }
  },
  computed: {
    ...mapGetters({
      currentWish: 'wish/currentWish'
    })
  },
  onLoad(options) {
    if (options.id) {
      this.id = options.id
      this.isEdit = true
      this.loadData()
    }
  },
  methods: {
    ...mapActions('wish', [
      'getWishDetail',
      'createWish',
      'updateWish'
    ]),
    formatDate,
    
    // 加载数据
    async loadData() {
      uni.showLoading({
        title: '加载中...'
      })
      
      try {
        await this.getWishDetail(this.id)
        
        // 填充表单数据
        this.form = {
          title: this.currentWish.title || '',
          description: this.currentWish.description || '',
          status: parseInt(this.currentWish.status) || 0,
          progress: this.currentWish.progress || 0,
          estimated_time: this.currentWish.estimated_time || ''
        }
      } catch (error) {
        console.error('加载数据失败', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } finally {
        uni.hideLoading()
      }
    },
    
    // 日期选择确认
    onDateConfirm(e) {
      this.form.estimated_time = e.year + '-' + e.month + '-' + e.day
    },
    
    // 提交表单
    async submitForm() {
      // 简单验证标题是否为空
      if (!this.form.title || this.form.title.trim() === '') {
        uni.showToast({
          title: '请输入愿望标题',
          icon: 'none'
        })
        return
      }
      
      uni.showLoading({
        title: this.isEdit ? '更新中...' : '创建中...'
      })
      
      try {
        const data = {
          ...this.form
        }
        
        if (this.isEdit) {
          data.id = this.id
          await this.updateWish(data)
        } else {
          await this.createWish(data)
        }
        
        uni.hideLoading()
        
        uni.showToast({
          title: this.isEdit ? '更新成功' : '创建成功',
          icon: 'success',
          duration: 1500,
          success: () => {
            // 使用 setTimeout 确保 toast 显示完成后再跳转
            setTimeout(() => {
              console.log('准备跳转到愿望列表页面')
              uni.reLaunch({
                url: '/pages/wish/index',
                success: () => {
                  console.log('跳转成功')
                },
                fail: (err) => {
                  console.error('跳转失败', err)
                }
              })
            }, 1600)
          }
        })
      } catch (error) {
        console.error(this.isEdit ? '更新失败' : '创建失败', error)
        uni.hideLoading()
        uni.showToast({
          title: this.isEdit ? '更新失败' : '创建失败',
          icon: 'none'
        })
      }
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
}

.progress-slider {
  position: relative;
  padding: 0 20rpx;
}

.slider-value {
  position: absolute;
  top: -50rpx;
  right: 20rpx;
  font-size: 28rpx;
  color: #2979ff;
  font-weight: bold;
}

.form-actions {
  margin-top: 50rpx;
  display: flex;
  justify-content: space-between;
}

.u-button {
  width: 45%;
}
</style> 